package isssr.dao.test;

import isssr.dao.factory.DAOFactory;
import isssr.dao.interfaces.RoleDAO;
import isssr.entity.src.Role;

import java.util.ArrayList;
import java.util.List;

public class RoleTestBuilder {


	private static Integer sequenceCounter = 0;
	

	private Integer getNextSequenceNumber()
	{
		return  sequenceCounter++;
	}
	
	private List<Role> registeredRoles;
	
	public RoleTestBuilder()
	{
		this.registeredRoles = new ArrayList<Role>();
	}
	
	private String buildStringField(String prefix)
	{
		return prefix + "_" + getNextSequenceNumber();
	}
	
	private Integer buildIntegerField(int min, int max)
	{
		return (int) (Math.random()*(max - min) + min);
	}
	
	private Integer buildIntegerField()
	{
		return buildIntegerField(0, 100);
	}
	
	
	public Role generateRole(String title, Integer level)
	{
		Role role;
		
		String newTitle;
		Integer newLevel;
		
		if(title == null)
			newTitle = buildStringField("title");
		else
			newTitle = title;

		if(level == null || level<0)
			newLevel = buildIntegerField();
		else
			newLevel = level;
		
		role = new Role(newTitle, newLevel);
		this.registeredRoles.add(role);
		
		return role;
	}

	public Role generateRole(String title)
	{
		return generateRole(title, null);
	}
	

	public Role generateRole(Integer level)
	{
		return generateRole(null, level);
	}
	
	
	public Role generateRole()
	{
		return generateRole(null, null);
	}
	
	public void unregisterRole(Role role)
	{
		this.registeredRoles.remove(role);
	}
	
	
	public void cleanUp()
	{
		RoleDAO roleDAO = DAOFactory.getDAOFactory().getRoleDAO();
		
		for(Role role : this.registeredRoles)
		{
			try
			{
				roleDAO.delete(role);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		
		this.registeredRoles.clear();
	}

}
